import { getRoleList } from './service';

const Model = {
  namespace: 'smRoleMgt',
  state: {
    roleListData: {},
    tableRef: {},
  },
  effects: {
    *getRoleList({ payload, resolve }, { call, put }) {
      const params = {
        ...payload,
        pageNum: payload.current,
        pageSize: payload.pageSize,
      };
      const response = yield call(getRoleList, params);

      if (!response.error) {
        const { records, pageNum, total } = response;

        for (let i = 0; i < records.length; i++) {
          let arr = '';
          if (records[i].roles.length) {
            for (let index = 0; index < records[i].roles.length; index++) {
              const element = records[i].roles[index].name;
              arr = `${arr}  ${element}`;
            }
          }
          records[i].role = arr;
        }
        const result = {
          data: records,
          page: pageNum,
          pageSize: payload.pageSize,
          success: true,
          total,
        };
        resolve && resolve(result);

        yield put({
          type: 'save',
          payload: {
            roleListData: result,
          },
        });
      }
    },

    // *addRole({ payload, resolve }, { call, put }) {
    //   const response = yield call(addRole, payload);
    //   if (!response.error) {
    //     resolve && resolve(response);
    //     message.success('角色新增成功！');

    //     yield put({
    //       type: 'tableReload',
    //     });
    //   }
    // },
    // *updateRole({ payload, resolve }, { call, put }) {
    //   const response = yield call(updateRole, payload);

    //   if (!response.error) {
    //     resolve && resolve(response);
    //     message.success('修改角色信息成功！');

    //     yield put({
    //       type: 'tableReload',
    //     });
    //   }
    // },
    // *deleteRoles({ payload }, { call, put }) {
    //   const response = yield call(deleteRoles, payload);

    //   if (!response.error) {
    //     message.success('角色删除成功！');
    //     yield put({
    //       type: 'tableReload',
    //     });
    //   }
    // },
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
    tableReload(state) {
      const tableRef = state.tableRef || {};
      setTimeout(() => {
        tableRef.current.reloadAndRest();
      }, 0);
      return { ...state };
    },
  },
};
export default Model;
